package controller

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"user-web/src/api"
	"user-web/src/biz"
	_ "user-web/src/biz/impl"
	"user-web/src/request"
)

type UserController struct {
}

func (uc *UserController) RegisterRouter(app *gin.Engine) {
	group := app.Group("/v1/user")
	group.POST("/login", uc.Login)
	group.POST("/info", uc.Info)
	group.POST("/edit", uc.Edit)
	group.POST("/upload", uc.Upload)
	group.POST("/refreshToken", uc.RefreshToken)
}

// Login 登录验证，登录成功返回前端token,其他url都需要有token验证才能访问
func (uc *UserController) Login(c *gin.Context) {
	var login request.LoginRequest
	if err := c.ShouldBindJSON(&login); err != nil {
		log.Printf("请求参数错误： %s \n", err)
		api.FailedParam(c, api.UserNamePassEmptyErr)
		return
	}
	userService := biz.RefUserService()
	c.JSON(http.StatusOK, userService.Login(&login))
}

// Info 查询用户信息
func (uc *UserController) Info(c *gin.Context) {
	var info request.InfoRequest
	if err := c.ShouldBindJSON(&info); err != nil {
		log.Printf("请求参数错误： %s \n", err)
		api.FailedParam(c, api.UserNameEmptyErr)
		return
	}
	userService := biz.RefUserService()
	c.JSON(http.StatusOK, userService.Query(&info))
}

// Upload 用户上传头像
func (uc *UserController) Upload(c *gin.Context) {
	var form request.UploadProfileRequest
	if err := c.ShouldBind(&form); err != nil {
		api.FailedParam(c, api.ProfileUploadErr)
		return
	}
	userService := biz.RefUserService()
	c.JSON(http.StatusOK, userService.UpdateProfile(&form))
}

// Edit 修改昵称
func (uc *UserController) Edit(c *gin.Context) {
	//参数绑定&参数校验
	var updateNickName request.EditNicknameRequest
	if err := c.ShouldBindJSON(&updateNickName); err != nil {
		log.Printf("请求参数错误： %s \n", err)
		api.FailedParam(c, api.UserNameNickNameEmptyErr)
		return
	}
	userService := biz.RefUserService()
	c.JSON(http.StatusOK, userService.UpdateNickname(&updateNickName))
}

// RefreshToken 刷新token
func (uc *UserController) RefreshToken(c *gin.Context) {
	username := c.Query("username")
	if username == "" {
		api.FailedParam(c, api.UserNameNickNameEmptyErr)
		return
	}
	userService := biz.RefUserService()
	c.JSON(http.StatusOK, userService.RefreshToken(username))
}
